# PowerShell script to bypass winCodeSign extraction issue
# This script packages the Electron app without code signing

Write-Host "Cleaning previous builds..." -ForegroundColor Cyan
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue ".\release\win-unpacked"

Write-Host "Running build..." -ForegroundColor Cyan
npm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "Build failed!" -ForegroundColor Red
    exit 1
}

Write-Host "Cleaning winCodeSign cache to avoid extraction errors..." -ForegroundColor Cyan
$cacheDir = "$env:LOCALAPPDATA\electron-builder\Cache\winCodeSign"
if (Test-Path $cacheDir) {
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $cacheDir
    Write-Host "Deleted cache: $cacheDir" -ForegroundColor Yellow
}

Write-Host "Running electron-builder with CSC disabled..." -ForegroundColor Cyan
$env:CSC_IDENTITY_AUTO_DISCOVERY = "false"
npx electron-builder --dir --win 2>&1 | Out-Null

# Check if the output exists regardless of exit code
# (winCodeSign error happens AFTER packaging completes)
if (Test-Path ".\release\win-unpacked\ElectronVue3Base.exe") {
    Write-Host "`n✓ Packaging successful!" -ForegroundColor Green
    Write-Host "Output directory: .\release\win-unpacked\" -ForegroundColor Cyan
    Write-Host "Executable: .\release\win-unpacked\ElectronVue3Base.exe" -ForegroundColor Green
    Write-Host "`nNote: winCodeSign warnings can be safely ignored for unpacked builds" -ForegroundColor Yellow
    exit 0
} else {
    Write-Host "`n✗ Packaging failed - executable not found!" -ForegroundColor Red
    exit 1
}
